// pages/zikao/zikao_academic/zikao_academic.js
const http = require('../../../utils/http.js');       // HTTP 请求工具
const tools = require('../../../utils/tools.js');     // 通用工具方法

Page({
  data: {
    // 学籍信息对象，只保存编码字段，名称通过映射得到
    zikao_academic_info: {
      english_name: '',            // 英文全名
      registered_residence_code: null,// 户籍代码，1城镇2农村255未采集
      pre_education_code: null,      // 考前学历编码
      occupation_code: null,         // 职业编码
      major_code: null,              // 专业编码
      registration_city_code: null,  // 报名市县编码(后端关联city_code)
      registration_point_code: null, // 报名点编码(后端关联id)
      is_currently_student: null,     // 在校生标记（0否、1是）
      household_address: ''        // 户口所在地编码，关联gk_registered_residence表中的code字段
    },
    // 下拉选项数组和选择下标
    residenceOptions: [{code:1,name:"城镇"},{code : 2,name:"农村"},{code:255,name:"未采集"}], 
    residenceIndex: null,
    educationOptions: [], educationIndex: null,
    occupationOptions: [], occupationIndex: null,
    majorOptions: [], majorIndex: null,
    cityOptions: [], cityIndex: null,
    pointOptions: [], pointIndex: null,
    studentOptions: ['否', '是'], studentIndex: null,
    addressOptions:[],addressIndex:null,
    // 录音识别相关状态
    recording: false,
    recordFilePath: '',
    buttonText: '开始录音'
  },

  /**
   * 生命周期函数：页面加载
   * 加载所有下拉框数据，然后从本地获取已保存的编码，并填充名称与下标
   */
  onLoad() {
    // 异步拉取选项接口
    const p1 = tools.fetchOptions2('/gaokao/GkRegisteredResidence/all', 'addressOptions', this);
    const p2 = tools.fetchOptions('/zikao/education/all', 'educationOptions', this);
    const p3 = tools.fetchOptions('/zikao/occupation/all', 'occupationOptions', this);
    const p4 = tools.fetchOptions('/major/list', 'majorOptions', this);
    const p5 = tools.fetchOptions3('/city/list', 'cityOptions', this);
    const p6 = tools.fetchOptions('/chengkao/examSite/all', 'pointOptions', this);

    Promise.all([p1, p2, p3, p4, p5, p6])
      .then(() => {
        // 获取本地存储的学籍信息编码
        const stored = wx.getStorageSync('zikao_academic_info');
        if (stored) {
          this.setData({ zikao_academic_info: stored });
          // 根据编码映射名称与下标
          this.updateIndexById(stored);
        }
      })
      .catch(err => console.error('选项加载失败', err));
  },

  /**
   * 根据编码填充对应的名称和下标
   * @param {Object} data 存储的编码对象
   */
  updateIndexById(data){
    // 根据存储的各字段的code,name ,id 查找对应的下标
    this.setData({
      residenceIndex : tools.findIndexByCode(this.data.residenceOptions , data.registered_residence_code),
      educationIndex : tools.findIndexByCode(this.data.educationOptions , data.pre_education_code),
      occupationIndex : tools.findIndexByCode(this.data.occupationOptions , data.occupation_code),
      majorIndex : tools.findIndexById(this.data.majorOptions , data.major_code),
      cityIndex : tools.findIndexByCode2(this.data.cityOptions , data.registration_city_code),
      pointIndex : tools.findIndexById(this.data.pointOptions , data.registration_point_code),
      addressIndex : tools.findIndexByCode(this.data.addressOptions , data.household_address),
      studentIndex : data.is_currently_student 
    })
  },

  /**
   * 通用文本输入处理：更新对应字段值
   */
  handleInput(e) {
    const f = e.currentTarget.dataset.field;
    this.setData({ [`zikao_academic_info.${f}`]: e.detail.value });
  },

  /**
   * 统一处理下拉选择
   * 根据 field 决定取值来源，并更新编码、名称及下标
   */
  handlePickerChange(e) {
    const f = e.currentTarget.dataset.field;
    const i = e.detail.value;
    let codeVal = '';
    switch (f) {
      case 'registered_residence_code':
        codeVal = this.data.residenceOptions[i].code;
        this.setData({ residenceIndex: i });
        break;
      case 'pre_education_code':
        codeVal = this.data.educationOptions[i].code;
        this.setData({ educationIndex: i });
        break;
      case 'occupation_code':
        codeVal = this.data.occupationOptions[i].code;
        this.setData({ occupationIndex: i });
        break;
      case 'major_code':
        codeVal = this.data.majorOptions[i].id;
        this.setData({ majorIndex: i });
        break;
      case 'registration_city_code':
        codeVal = this.data.cityOptions[i].cityCode;
        this.setData({ cityIndex: i });
        break;
      case 'registration_point_code':
        codeVal = this.data.pointOptions[i].id;
        this.setData({ pointIndex: i });
        break;
      case 'is_currently_student':
        codeVal = i;
        this.setData({ studentIndex: i });
        break;
      case 'household_address':
        codeVal = this.data.addressOptions[i].code;
        this.setData({ addressIndex: i });
        break;
    }
    // 只存编码到数据对象中
    this.setData({ [`zikao_academic_info.${f}`]: codeVal });
  },

  /**
   * 提交并本地保存，仅提交编码字段
   */
  handleSubmit() {
    // 获取存储的信息
    const d = this.data.zikao_academic_info;
    // 检查信息是否有修改
    // 待检查字段对照表
    const fieldsToCheck = [
      'english_name',
      'registered_residence_code',
      'pre_education_code',
      'occupation_code',
      'major_code',
      'registration_city_code',
      'registration_point_code',
      'is_currently_student',
      'household_address'
    ];
    // 获取本地信息
    const stordInfo = wx.getStorageSync('zikao_academic_info');
    if(tools.checkDataChanged(d,stordInfo,fieldsToCheck)){
      const idNumber = wx.getStorageSync('base_candidate_info').id_number;
      // 构建postData
      const postData = {
        idNumber: idNumber,
        englishName: d.english_name,
        registeredResidenceCode: d.registered_residence_code,
        preEducationCode: d.pre_education_code,
        occupationCode: d.occupation_code,
        majorCode: d.major_code,
        registrationCityCode: d.registration_city_code,
        registrationPointCode: d.registration_point_code,
        isCurrentlyStudent: d.is_currently_student,
        householdAddress: d.household_address
      };
      http.post('/zikao/registration/upsert', postData)
      .then(res => {
        if (res.data.code === 200) {
          // 更新本地存储
          wx.setStorageSync('zikao_academic_info', d);
          wx.showToast({ title: '保存成功' });
          // 跳转页面
          wx.navigateTo({url:"/pages/zikao/zikao_page3/zikao_page3"})
        }
      })
      .catch(err => {
        wx.showToast({ title: '保存失败', icon: 'none' });
        console.error('学籍信息更新失败',err);
      });
    }else{
      // 不用更新后端内容，直接跳转
      // 跳转页面
      wx.navigateTo({url:"/pages/zikao/zikao_page3/zikao_page3"})
    }
  },

  // 语音功能区
  /**
   * 切换录音状态：开始/停止录音
   */
  toggleRecording() {
    if (this.data.recording) {
      // 停止录音
      this.setData({ recording: false, buttonText: '开始录音' });
      const manager = wx.getRecorderManager();
      manager.stop();
      manager.onStop(res => {
        wx.setStorageSync('recordPath', res.tempFilePath)
        this.setData({ recordFilePath: res.tempFilePath , buttonText : '开始录音'});
      });
    } else {
      // 开始录音，需权限
      tools.checkRecordPermission()
        .then(() => {
          this.setData({ recording: true, buttonText: '停止录音' });
          const manager = wx.getRecorderManager();
          manager.start({ format: 'wav', duration: 60000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 96000 });
        })
        .catch(err => wx.showToast({ title: err.message, icon: 'none' }));
    }
  },

  /**
   * 上传录音并发起语音识别
   */
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
     wx.showToast({ title: '请先录音', icon: 'none' });
     return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.zikaoExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        this.mapVoiceResult(res.data);
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },

  /**
   * 将语音识别返回的名称映射到对应编码，并更新展示名称及下标
   * @param {Object} fields 语音识别接口返回字段，如 { registered_residence_name: 'xxx', ... }
   */
  mapVoiceResult(fields) {
    console.log("this is map fields is :",fields);
    // 可直接赋值字段
    // , 'is_currently_student'
    const directFields = ['english_name']
    directFields.forEach(key=>{
      if(!fields[key].includes("未知")){
        this.setData({[`zikao_academic_info.${key}`]:fields[key]})
      }
    })
    // 对户籍类型进行特殊处理
    if(fields["registered_residence"]){
      this.setData({[`zikao_academic_info.registered_residence_code`]:fields["registered_residence"]})
    }
    // 需要根据对应的name查找对应的id和code，进行赋值和更新下标
    const mapping = {
      pre_education: ['educationOptions', 'pre_education_code'],
      occupation: ['occupationOptions', 'occupation_code'],
      major: ['majorOptions', 'major_code'],
      registration_city: ['cityOptions', 'registration_city_code'],
      registration_point: ['pointOptions', 'registration_point_code'],
      household_address:['addressOptions', 'household_address']
    };
    Object.entries(mapping).forEach(([key, [optArr, codeKey]]) => {
      let id = '';
      if (!fields[key].includes("未知")) {
        // 通过name查找对应的id或者code
        if(key == 'registration_city'){
          id = tools.findCodeByName2(this.data[optArr], fields[key])
        }else{
          id = tools.findCodeByName(this.data[optArr], fields[key])
        }
        // 给每一项先赋值
        if(id){
          this.setData({
            [`zikao_academic_info.${codeKey}`]: id,
          })
        }
        
      }
    });
    // 根据字段code进行更新下标
    this.updateIndexById(this.data.zikao_academic_info);
  }
});